package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.injector.methods.SelectOne;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //判断是否为null
        if(multipartFile == null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //生成文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //获取源文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取源文件后缀名
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            //上传文件
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("图片已上传至MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败");
        }
        //保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0); // 0是图片
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        return ResponseResult.okResult(wmMaterial);

    }

    /**
     * 查询图片
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //校验参数(没有值就设置默认值)
        dto.checkParam();
        //分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if(dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //添加用户条件
        wrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //按照时间倒序排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //查询
        page = page(page,wrapper);
        //返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;

    }

    /**
     * 收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId,id);
        //查询素材
        WmMaterial wmMaterial = getOne(wrapper);
        //修改素材状态
        wmMaterial.setIsCollection((short) 1);
        boolean flag = updateById(wmMaterial);
        return flag ? ResponseResult.okResult("收藏成功") : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"收藏错误");
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId,id);
        //查询素材
        WmMaterial wmMaterial = getOne(wrapper);
        //修改素材状态
        wmMaterial.setIsCollection((short) 0);
        boolean flag = updateById(wmMaterial);
        return flag ? ResponseResult.okResult("取消收藏成功") : ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"取消收藏错误");
    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {

        //查询素材是否有关联
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> list = wmNewsMaterialMapper.selectList(wrapper);
        if(list.size() > 0){
            //查到了证明有关联
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"素材和文章有关联");
        }
        //删除minio
        fileStorageService.delete(wmMaterialMapper.selectById(id).getUrl());
        //删除数据库数据
        return ResponseResult.okResult(wmMaterialMapper.deleteById(id));
    }


}
